package org.dromara.pc.config;

import freemarker.template.TemplateModelException;
import jakarta.annotation.PostConstruct;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.cms.domain.bo.CmsArticleBo;
import org.dromara.cms.domain.bo.CmsCategoryBo;
import org.dromara.cms.domain.bo.CmsConfigBo;
import org.dromara.cms.domain.vo.CmsArticleVo;
import org.dromara.cms.domain.vo.CmsCategoryVo;
import org.dromara.cms.domain.vo.CmsConfigVo;
import org.dromara.cms.service.ICmsArticleService;
import org.dromara.cms.service.ICmsCategoryService;
import org.dromara.cms.service.ICmsConfigService;
import org.dromara.system.domain.vo.SysOssVo;
import org.dromara.system.service.ISysOssService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Freemarker 配置
 */
@Slf4j
@Configuration
@RequiredArgsConstructor
public class FreemarkerConfig {

    private final freemarker.template.Configuration configuration;
    private final ICmsConfigService configService;
    private final ICmsCategoryService cmsCategoryService;
    private final Map<String, String> templateMapping = new ConcurrentHashMap<>();

    @Autowired
    private ICmsCategoryService categoryService;

    @Autowired
    private ICmsArticleService articleService;

    @Autowired
    private ISysOssService ossService;

    @PostConstruct
    public void init() {
        try {
            // 初始化全局变量
            initBasicVariables();
            // 初始化站点配置
            initSiteConfig();
            // 初始化菜单分类
            initCategoryMenu();
            // 初始化新闻分类
            initNewsCategories();
            // 初始化产品分类
            initProductCategories();

            log.info("Freemarker配置初始化成功");
        } catch (Exception e) {
            log.error("Freemarker配置初始化失败: {}", e.getMessage());
        }
    }

    // 添加刷新配置的方法
    public void refreshConfig() {
        try {
            // 初始化全局变量
            initBasicVariables();
            // 初始化站点配置
            initSiteConfig();
            // 初始化菜单分类
            initCategoryMenu();
            // 初始化新闻分类
            initNewsCategories();
            // 初始化产品分类
            initProductCategories();

            log.info("Freemarker配置刷新成功");
        } catch (Exception e) {
            log.error("Freemarker配置刷新失败: {}", e.getMessage());
        }
    }

    // 初始化基本变量
    private void initBasicVariables() throws TemplateModelException {
        configuration.setSharedVariable("projectName", "RuoYi-Vue-Plus企业网站");
    }

    // 初始化站点配置
    private void initSiteConfig() throws TemplateModelException {
        List<CmsConfigVo> configs = configService.queryList(new CmsConfigBo());
        if (!configs.isEmpty()) {
            // 处理 Logo URL
            for (CmsConfigVo config : configs) {
                if ("site_logo".equals(config.getConfigKey())) {
                    String logoId = config.getConfigValue();
                    if (logoId != null && !logoId.isEmpty()) {
                        try {
                            SysOssVo ossFile = ossService.getById(Long.parseLong(logoId));
                            if (ossFile != null) {
                                config.setConfigValue(ossFile.getUrl());
                            }
                        } catch (Exception e) {
                            log.error("处理Logo URL失败: {}", e.getMessage());
                        }
                    }
                    break;
                }
            }

            log.info("站点配置: {}", configs);
            configuration.setSharedVariable("site", configs);
        }
    }

    // 初始化菜单分类
    private void initCategoryMenu() throws TemplateModelException {
        CmsCategoryBo menuBo = new CmsCategoryBo();
        menuBo.setIsShow("2");
        List<CmsCategoryVo> categories = cmsCategoryService.queryList(menuBo);
        if (!categories.isEmpty()) {
            configuration.setSharedVariable("category", categories);
        }

        // 获取当前请求
        ServletRequestAttributes attributes =
            (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            String path = request.getRequestURI();

            // 获取最后一个斜杠后的内容
            String lastPath = path;
            if (path.contains("/")) {
                lastPath = path.substring(path.lastIndexOf("/") + 1);
            }

            // 如果是根路径，设置为 index
            if (lastPath.isEmpty()) {
                lastPath = "index";
            }

            log.info("当前处理的路径: {}, 最后一段: {}", path, lastPath);

            CmsCategoryBo bo = new CmsCategoryBo();
            bo.setPath(lastPath);
            List<CmsCategoryVo> category = categoryService.queryList(bo);

            if (category.isEmpty()) {
                CmsArticleBo cmsArticleBo = new CmsArticleBo();
                cmsArticleBo.setSlug(lastPath);
                List<CmsArticleVo> cmsArticleVos = articleService.queryList(cmsArticleBo);
                if (!cmsArticleVos.isEmpty()) {
                    configuration.setSharedVariable("categorySeo", cmsArticleVos.get(0));
                }
            } else {
                configuration.setSharedVariable("categorySeo", category.get(0));
            }
        }
    }

    // 初始化新闻分类
    private void initNewsCategories() throws TemplateModelException {
        // 先查询新闻一级分类
        CmsCategoryBo parentBo = new CmsCategoryBo();
        parentBo.setTemplate("news.html");
        List<CmsCategoryVo> parentCategory = categoryService.queryList(parentBo);

        if (!parentCategory.isEmpty()) {
            Long parentId = parentCategory.get(0).getId();
            log.info("新闻一级分类ID: {}", parentId);

            CmsCategoryBo queryBo = new CmsCategoryBo();
            queryBo.setParentId(parentId);
            List<CmsCategoryVo> newsCategories = categoryService.queryList(queryBo);

            // 创建一个新的列表来存储带有文章的分类
            List<Map<String, Object>> categoriesWithArticles = new ArrayList<>();

            for (CmsCategoryVo category : newsCategories) {
                Map<String, Object> categoryMap = new HashMap<>();
                categoryMap.put("category", category);

                // 查询该分类下的文章
                CmsArticleBo articleBo = new CmsArticleBo();
                articleBo.setCategoryId(category.getId());
                List<CmsArticleVo> articles = articleService.queryList(articleBo);

                log.info("分类[{}] id={} 查询到的文章数量: {}",
                    category.getTitle(), category.getId(), articles.size());

                categoryMap.put("articles", articles);
                categoriesWithArticles.add(categoryMap);
            }

            // 设置到全局变量
            configuration.setSharedVariable("news_categories", categoriesWithArticles);
        }
    }

    // 初始化产品分类
    private void initProductCategories() throws TemplateModelException {
        // 先查询产品一级分类
        CmsCategoryBo parentBo = new CmsCategoryBo();
        parentBo.setTemplate("products.html");
        List<CmsCategoryVo> parentCategory = categoryService.queryList(parentBo);

        if (!parentCategory.isEmpty()) {
            // 获取产品一级分类的ID
            Long parentId = parentCategory.get(0).getId();

            // 查询产品子分类
            CmsCategoryBo queryBo = new CmsCategoryBo();
            queryBo.setParentId(parentId);  // 设置父级ID，只查询子分类
            List<CmsCategoryVo> productCategories = categoryService.queryList(queryBo);

            // 设置到全局变量
            configuration.setSharedVariable("nav_products", productCategories);
        }
    }

    // 添加URL映射
    public void addTemplateMapping(String url, String template) {
        String normalizedUrl = normalizeUrl(url);
        String normalizedTemplate = normalizeTemplate(template);
        templateMapping.put(normalizedUrl, normalizedTemplate);
        log.debug("添加URL映射: {} -> {}", normalizedUrl, normalizedTemplate);
    }

    // 获取模板
    public String getTemplate(String url) {
        String normalizedUrl = normalizeUrl(url);
        log.debug("处理URL: {} -> {}", url, normalizedUrl);

        // 处理首页请求
        if (isIndexRequest(normalizedUrl)) {
            return "index";
        }

        // 获取模板
        String template = templateMapping.get(normalizedUrl);
        if (template == null) {
            log.debug("未找到模板，返回首页");
            return "error/404";
        }

        log.debug("找到模板: {}", template);
        return template;
    }

    // 检查是否是首页请求
    private boolean isIndexRequest(String url) {
        return url.isEmpty() || "index".equals(url);
    }

    // 规范化URL
    private String normalizeUrl(String url) {
        // 移除开头斜杠和结尾.html
        String normalized = url.startsWith("/") ? url.substring(1) : url;
        normalized = normalized.endsWith(".html") ? normalized.substring(0, normalized.length() - 5) : normalized;

        // 移除末尾斜杠
        while (normalized.endsWith("/")) {
            normalized = normalized.substring(0, normalized.length() - 1);
        }

        // 处理路径层级
        String[] parts = normalized.split("/");
        if (parts.length == 1) {
            return parts[0];
        } else if (parts.length > 1) {
            return parts[0] + "/" + String.join("/", Arrays.copyOfRange(parts, 1, parts.length));
        }

        return normalized;
    }

    // 规范化模板名称
    private String normalizeTemplate(String template) {
        return template.endsWith(".html") ? template.substring(0, template.length() - 5) : template;
    }
}
